import React, { useState, useEffect } from "react";
import {
  message,
  Drawer,
  Form,
  Input,
  Button,
  Radio,
  InputNumber,
  Select,
  Spin,
} from "antd";
import {
  upadataItemField,
  getDetail,
  addItemField,
  getDatatablelist,
} from "../api";
import { getTree, getSourcedataList } from "../../../SourceData/DataItem/api";
import { set } from "lodash";

const { Option } = Select;

const UpdateItem = (props) => {
  // 结构化数据
  const {
    visible,
    onCancel,
    onSuccess,
    data,
    type,
    catagolueid,
    dbsourceid,
    currentIndex = 0,
  } = props;

  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const [treeData, setTreeData] = useState([]); // 源数据库

  const [unitData, setUnitData] = useState([]); // 源数据库分类
  const [sourcedata, setSourcedata] = useState([]); // 源数据库表 列表

  // 详情
  const getDetailData = () => {
    const paylaod = {
      id: data.id,
    };
    setLoading(true);
    getDetail(paylaod).then((res) => {
      setLoading(false);
      if (res.code === 0) {
        getUnitdata({ dataUnitId: res.data.unitid });
        getDatatablelistData({ sourceid: res.data.sourceid });
        form.setFieldsValue({ ...res.data });
      } else {
        message.error(res.msg || "获取详情失败");
      }
    });
  };

  const getTreeData = () => {
    setLoading(true);
    getTree().then((res) => {
      setLoading(false);
      if (res.code === 0) {
        setTreeData(res.data);
      } else {
        message.error(res.msg || "获取详情失败");
      }
    });
  };

  useEffect(() => {
    if (type === "updata" && visible === true) {
      getDetailData();
    } else {
      form.resetFields();
    }
    if (visible) {
      getTreeData();
    }
    form.setFieldsValue({ tableState: "1" });
  }, [visible]);

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 15 },
  };

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = (values) => {
    const hide = message.loading("正在添加");
    setLoading(true);
    upadataItemField({ ...values, id: data.id }).then((res) => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || "修改失败，请重试");
      }
    });
  };
  /**
   * @en-US Update node
   * @zh-CN 添加
   *
   * @param values
   */
  const addData = (values) => {
    const hide = message.loading("正在添加");
    setLoading(true);

    addItemField({ ...values }).then((res) => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || "添加失败，请重试");
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then((values) => {
      values.catagolueid = catagolueid;
      values.dbsourceid = dbsourceid;
      if (type === "updata") updataData(values);
      if (type === "add") addData(values);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  /**
   * @zh-CN 获取数据源库
   * @param value
   */
  const getUnitdata = (value) => {
    setLoading(true);
    getSourcedataList(value).then((res) => {
      setLoading(false);
      if (res.code === 0) {
        setUnitData(res.data);
      } else {
        message.error(res.msg || "请求失败，请重试");
      }
    });
  };

  /**
   * @zh-CN 获取数据源库表名
   * @param value
   */
  const getDatatablelistData = (value) => {
    setLoading(true);
    getDatatablelist(value).then((res) => {
      setLoading(false);
      if (res.code === 0) {
        setSourcedata(res.data);
      } else {
        message.error(res.msg || "请求失败，请重试");
      }
    });
  };
  /**
   * @zh-CN 选择数据源库分类
   *
   * @param values
   */
  const selUnitidData = (value) => {
    const playlaod = { dataUnitId: value };
    form.setFieldsValue({ sourceid: null, tableName: null });
    getUnitdata(playlaod);
  };

  /**
   * @zh-CN 选择数据源库
   *
   * @param values
   */
  const selSourceData = (value) => {
    const playlaod = { sourceid: value };
    form.setFieldsValue({ tableName: null });
    getDatatablelistData(playlaod);
  };

  return (
    <>
      <Drawer
        getContainer={false}
        width={640}
        title={type === "updata" ? "修改" : "添加"}
        visible={visible}
        onClose={modelClose}
        maskClosable={false}
        footer={
          <div
            style={{
              textAlign: "right",
            }}
          >
            <Button onClick={modelClose} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button
              onClick={sendData}
              type="primary"
              loading={loading}
              disabled={loading}
            >
              保存
            </Button>
          </div>
        }
      >
        <Spin spinning={loading}>
          <Form {...formItemLayout} name="control-ref" form={form}>
            <Form.Item
              label="目标表名称"
              name="tableName"
              rules={[{ required: true }]}
            >
              <Input maxLength={20} placeholder="请输入目标表名称" />
            </Form.Item>
            <Form.Item
              label="源数据库分类"
              name="unitid"
              rules={[{ required: true }]}
            >
              <Select placeholder="请选择源数据库分类" onChange={selUnitidData}>
                {treeData.map((item) => {
                  return (
                    <Option value={item.key} key={item.key}>
                      {item.title}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item
              label="源数据库"
              name="sourceid"
              rules={[{ required: true }]}
            >
              <Select placeholder="请选择数据源库" onChange={selSourceData}>
                {unitData.map((item) => {
                  return (
                    <Option value={item.id} key={item.id}>
                      {item.name}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>

            <Form.Item
              label="源数据库表名"
              name="sourceTable"
              rules={[{ required: true }]}
            >
              <Select
                placeholder="请选择数据源库表"
                showSearch
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >=
                  0
                }
              >
                {sourcedata.map((item) => {
                  return (
                    <Option value={item.name} key={item.id}>
                      {item.name}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item name="tableState" label="激活状态">
              <Radio.Group>
                <Radio value="0">禁用</Radio>
                <Radio value="1">激活</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="备注" name="remarks">
              <Input.TextArea
                maxLength={200}
                allowClear
                placeholder="请输入备注 最多200字"
              />
            </Form.Item>
          </Form>
        </Spin>
      </Drawer>
    </>
  );
};

export default UpdateItem;
